package com.javaeedev.junit;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Multi-thread read/write problem has been fixed in this version, using 
 * JDK 5 ReadWriteLock.
 * 
 * @author Xuefeng
 */
public class Cache {

    private char[] buffer = "0000000000".toCharArray();

    private ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private Lock readLock = rwLock.readLock();
    private Lock writeLock = rwLock.writeLock();

    public void write(char c) {
        writeLock.lock();
        try {
            for(int i=0; i<buffer.length; i++)
                buffer[i] = c;
        }
        finally {
            writeLock.unlock();
        }
    }

    public char[] read() {
        readLock.lock();
        try {
            char[] cs = new char[buffer.length];
            for(int i=0; i<buffer.length; i++)
                cs[i] = buffer[i];
            return cs;
        }
        finally {
            readLock.unlock();
        }
    }
}
